import { Modal, message, Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React from 'react';

const UploadFileForm = props => {
  const { visible, onSuccess, onCancel, callback } = props;

  // Handlers
  const handleSubmit = async () => {
    onSuccess();
    callback(matrixs);
  };
  let matrixs = [];
  let fileNames = [];
  const p = {
    defaultFileList: [],
    multiple: true,
    name: 'file',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      const { file } = info;
      if (file.status === 'removed' && fileNames.includes(file.name)) {
        let removeIndex = fileNames.indexOf(file.name);
        fileNames.splice(removeIndex, 1);
        matrixs.splice(removeIndex, 1);
      }
    },
    beforeUpload(file, fileList) {
      let reader = new FileReader(); //new一个FileReader实例
      if (/text+/.test(file.type)) {
        //判断文件类型，是不是text类型
        reader.onload = function () {
          const matrix = this.result
            .split('\n')
            .map(item => item.split(' ').map(item => parseInt(item)));
          if (matrix.length > matrix[0].length) matrix.pop();
          if (matrix.length !== matrix[0].length) {
            file.status = 'error';
            message.error('上传的文件必须为邻接矩阵的txt文件');
            return false;
          }
          matrixs.push(matrix);
          fileNames.push(file.name);
          message.success('上传成功');
        };
        reader.readAsText(file);
      } else {
        file.status = 'error';
      }
      return false;
    },
  };

  // Renders
  return (
    <Modal
      maskClosable={false}
      visible={visible}
      title={'导入测试文件'}
      okText={'提交'}
      cancelText={'取消'}
      onOk={handleSubmit}
      onCancel={onCancel}
      destroyOnClose={true}
    >
      <Upload {...p}>
        <Button icon={<UploadOutlined />} size="middle">
          click to upload
        </Button>
      </Upload>
    </Modal>
  );
};
export default UploadFileForm;
